<!-- 医保收费弹窗 -->
<template>
  <a-modal :open="open" title="收费" width="900px" style="height: 86%" :footer="null" centered @cancel="onCancel">
    <div class="h-full flex flex-col">
      <div class="flex-1">
        <div class="flex flex-wrap">
          <div class="w-full flex">
            <div class="w-1/3 text-left">
              <span class="font-bold">医疗总金额: </span>
              <span class="text-base font-semibold">￥{{ formatAmount(realAmount) }}</span>
            </div>
            <div class="w-1/3 text-center">
              <span class="font-bold">医保支付: </span>
              <span class="text-base font-semibold">￥{{ formatAmount(chargeData.ybzf) }}</span>
            </div>
            <div class="w-1/3 text-right mr-3">
              <span class="font-bold">应收金额: </span>
              <span class="text-base font-semibold text-red-500">￥{{ formatAmount(chargeData.ysje) }}</span>
            </div>
          </div>
        </div>
        <CouponCard ref="couponRef" class="mt-2" @success="onSuccessCoupon" />
        <div class="w-full flex justify-between mt-4">
          <div class="text-title">分币误差</div>
          <div class="text-right mr-3">
            <span class="font-bold">分币: </span>
            <span class="text-base font-semibold text-red-500">￥{{ formatAmount(differenceAmount) }}</span>
          </div>
        </div>
        <a-divider class="my-4" />
        <a-form :model="formState" class="cost-form-style pb-4 overflow-auto" :label-col="{ style: { width: '100px' } }">
          <div class="flex justify-between">
            <div class="text-title">收费方式</div>
            <div class="text-right mr-3">
              <span class="font-bold">实收金额: </span>
              <span class="text-base font-semibold text-red-500">￥{{ formatAmount(chargeData.ysje) }}</span>
            </div>
          </div>
          <div class="flex flex-wrap mt-6 h-72 overflow-y-auto">
            <a-form-item v-for="item in chargeTypeList" :key="item.id" :label="item.zffsmc" class="w-1/2">
              <a-input-group class="!flex">
                <a-input
                  :key="item.zffsdm"
                  v-model:value="formState[item.zffsdm]"
                  v-input-selection
                  size="large"
                  placeholder="0.00"
                  @blur="onBlur(item.zffsdm)"
                  @change="handlerChangePrice(item.zffsdm)"
                >
                  <template #prefix> <span class="text-gray-400">￥</span> </template>
                </a-input>
                <a-button class="!w-10 !rounded-l-none border-l-0" size="large" @click="onclickAllPrice(item)">
                  <template #icon>
                    <ArrowLeftOutlined class="text-gray-400 text-xs" />
                  </template>
                </a-button>
              </a-input-group>
            </a-form-item>
          </div>
          <a-divider />
        </a-form>
      </div>
      <div class="w-full flex justify-between !mb-0">
        <div class="text-right mr-3">
          <span class="font-bold">找零: </span>
          <span class="text-base font-semibold text-red-500">￥{{ formatAmount(changeAmount) }}</span>
        </div>
        <div class="flex text-right">
          <a-button type="default" class="mr-4" @click="onCancel">取消</a-button>
          <a-button type="primary" :disabled="disabledState" @click="onOk">确定</a-button>
        </div>
      </div>
    </div>
  </a-modal>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import { formatAmount } from '@/utils/format.js'
import CouponCard from '@/components/CouponCard'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  registerPrice: {
    type: Number,
    default: () => 0
  },
  difference: {
    type: Number,
    default: () => 0
  },
  isPreferential: {
    type: Boolean,
    default: true
  },
  chargeData: {
    type: Object,
    default: () => ({})
  },
  isShowAmount: {
    type: Boolean,
    default: true
  }
})
const chargeTypeList = ref([])
const discountAmount = ref('0.00') // 优惠金额
const differenceAmount = ref(0) // 分币误差
const changeAmount = ref(0) // 找零
const formState = ref({})
const realAmount = ref(0)
const ePayTotal = ref(0) // 电子支付的总和
const priceAll = ref(0) // 全部的总和
const disabledState = ref(true)

// 实收金额 = 应收金额-优惠金额-分币误差
// const realAmount = computed(() => {
//   return props.registerPrice - Number(discountAmount.value) - Number(differenceAmount.value)
// })
// 找零=现金+电子支付-实收金额
const countSmallChange = () => {
  const zero = +formState.value['xjzf'] + ePayTotal.value - Number(realAmount.value)
  changeAmount.value = formatAmount(zero)
}
const handlerChangePrice = (zffsdm = '') => {
  ePayTotal.value = 0
  priceAll.value = 0
  // 限制输入内容的范围
  formState.value[zffsdm] = formState.value[zffsdm].replace(/[^\d.]/g, '')
  // 计算电子支付的总和
  for (const key in formState.value) {
    if (key !== 'xjzf') {
      ePayTotal.value += Number(formState.value[key])
    }
  }
  // 判断电子支付的总和是否大于实收金额
  if (ePayTotal.value > realAmount.value) {
    formState.value[zffsdm] = null
    formState.value['xjzf'] = '0.00'
    changeAmount.value = 0
    return message.error('电子支付累计金额不可大于实收金额')
  }
  // 判断当前输入的是否是现金金额
  if (zffsdm === 'xjzf') {
    // 如果现金+电子支付>实收金额，计算找零
    if (+formState.value['xjzf'] + ePayTotal.value > +realAmount.value) {
      countSmallChange()
    } else {
      changeAmount.value = 0
    }
  } else {
    // 判断电子支付金额是否等于0，如果不等于，判断实收金额是否大于电子支付金额或者是否相等
    if (ePayTotal.value !== 0) {
      if (realAmount.value > ePayTotal.value || realAmount.value === ePayTotal.value) {
        // 现金=实收金额-电子支付
        const cash = realAmount.value - ePayTotal.value < 0 ? 0 : formatAmount(realAmount.value - ePayTotal.value)
        formState.value['xjzf'] = +cash ? formatAmount(cash) : '0.00'
        countSmallChange()
      }
    } else {
      formState.value['xjzf'] = '0.00'
    }
  }

  for (const key in formState.value) {
    priceAll.value += Number(formState.value[key])
  }
  if (
    Number(formatAmount(priceAll.value)) > Number(formatAmount(realAmount.value)) ||
    Number(formatAmount(priceAll.value)) === Number(formatAmount(realAmount.value))
  ) {
    disabledState.value = false
  } else {
    disabledState.value = true
  }
}

// 判断优惠金额和支付，鼠标离开保留两位
const onBlur = (zffsdm = '') => {
  if (zffsdm !== '') {
    formState.value[zffsdm] = formState.value[zffsdm] ? formatAmount(formState.value[zffsdm]) : ''
  } else {
    discountAmount.value = discountAmount.value ? formatAmount(discountAmount.value) : ''
  }
}
// 单项全部收费
const onclickAllPrice = (item) => {
  formState.value = {}
  formState.value = { [item.zffsdm]: formatAmount(realAmount.value) }
  changeAmount.value = 0
  disabledState.value = false
}
const onRest = () => {
  discountAmount.value = '0.00'
  formState.value = {}
  changeAmount.value = 0
}

const getChargeTypeList = async () => {
  const { code, data } = await post('/outp/oupCharge/getChargeTypeList')
  if (code !== 0) return
  chargeTypeList.value = data
}

const onOk = async () => {
  const chargeData = { ...formState.value }
  chargeTypeList.value.forEach((item) => {
    chargeData[item.zffsdm] = chargeData[item.zffsdm] ? chargeData[item.zffsdm] : 0
  })
  const params = {
    ...chargeData,
    change: changeAmount.value,
    fbyh: chargeData.fbwc,
    yhje: discountAmount.value,
    ysje: formatAmount(props.registerPrice),
    ssje: formatAmount(realAmount.value)
  }
  emit('success', params)
  onCancel()
}

// const onDiscountInput = () => {
//   formState.value = {}
//   changeAmount.value = 0
//   discountAmount.value = discountAmount.value.replace(/[^\d.]/g, '')
//   if (+discountAmount.value > +props.registerPrice) {
//     message.error('优惠金额不能大于应收金额')
//     discountAmount.value = '0.00'
//   }
//   getDiscountAmount()
// }
const getDiscountAmount = async () => {
  // const { code, data } = await post('/outp/oupCharge/getPennyDiscount', {
  //   ysje: Number(props.registerPrice), //应收金额
  //   yhje: Number(discountAmount.value) //优惠金额
  // })
  // if (code !== 0) return
  // differenceAmount.value = props.difference !== 0 ? props.difference : data.fbwc
  // realAmount.value = data.ssje
  realAmount.value = Number(props.chargeData.ssje)
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      getDiscountAmount()
      disabledState.value = true
    }
    onRest()
  },
  { immediate: true }
)

const onCancel = () => {
  emit('update:open', false)
}
onMounted(() => {
  getChargeTypeList()
})
</script>
<style lang="less" scoped>
.cost-form-style {
  :deep(.ant-form-item) {
    padding: 0 3px;

    .ant-form-item-label {
      width: 75px;
      padding-top: 4px;

      label {
        color: #5d5d5d;
        font-size: 16px;
      }
    }

    .ant-form-item-control {
      flex: none;
      width: 240px;
      color: #2b2b2b;
      font-size: 15px;

      .ant-input {
        text-align: right;
      }
    }
  }

  .ant-divider {
    margin: 12px 0;
  }
}

.in-title {
  color: #a4adb3;
}
.text-title {
  position: relative;
  // width: 100%;
  margin-bottom: 8px;
  padding-left: 16px;
  font-weight: 600;
  &::after {
    position: absolute;
    top: calc(50% - 8px);
    left: 0;
    width: 4px;
    height: 16px;
    background-color: var(--primary-color);
    content: '';
  }
}
</style>
<style>
.full-modal .ant-modal-content {
  height: 100%;
}
.full-modal .ant-modal-body {
  height: calc(100% - 52px);
  overflow-y: auto;
}
</style>
